const indexDB = window.indexedDB
function dbActionWrap(action) {
    return new Promise((resolve, rejected) => {
        action.onsuccess = () => resolve(action.result)
        action.onerror = () => rejected(action.error)
    })
}
class DiskStore {
    constructor(dbName, storeName) {
        this.dbName = dbName
        this.storeName = storeName
    }
    async getStore(actionMode, storeName = this.storeName) {
        const { dbName } = this
        const connect = indexDB.open(dbName)
        return new Promise(resolve => {
            connect.onsuccess = e => {
                const db = e.target.result
                const version = parseInt(db.version)
                const v = !db.objectStoreNames.contains(storeName) ? version + 1 : version
                db.close()
                const sr = indexDB.open(dbName, v)
                sr.onupgradeneeded = e => {
                    const { result } = e.target
                    if (!result.objectStoreNames.contains(storeName)) {
                        result.createObjectStore(storeName)
                    }
                }
                sr.onsuccess = e => {
                    const { result } = e.target
                    const store = result.transaction(storeName, actionMode).objectStore(storeName)
                    resolve(store)
                    e.target.result.close()
                }
            }
        })
    }
    async getItem(key) {
        const store = await this.getStore('readonly')
        return dbActionWrap(store.get(key))
    }
    async setItem(key, value) {
        const store = await this.getStore('readwrite')
        return dbActionWrap(store.put(value, key))
    }
    async remove(key) {
        const store = await this.getStore('readwrite')
        return dbActionWrap(store.delete(key))
    }
    async clear(key) {
        const store = await this.getStore('readwrite')
        return dbActionWrap(store.clear())
    }
}

export default DiskStore